package com.analyse.stock.vo;

import com.analyse.stock.enums.ResultCodeEnums;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * 结果集封装
 * Created by liang on 2021-03-11.
 */
@Slf4j
public class ResultUtils {
    public static ResultVo success(Object data){
        ResultVo resultVO = new ResultVo();
        resultVO.setCode(ResultCodeEnums.OK.getCode());
        resultVO.setData(data);
        resultVO.setMsg(ResultCodeEnums.OK.getMsg());
        return resultVO;
    }

    public static ResultVo success() {
        return success(null);
    }

    /**
     * 成功
     * @param data data
     * @param <T> T
     * @return ResultVo<T>
     */
    public static <T> ResultVo<T> ok(T data){
        ResultVo<T> resultVO = new ResultVo<>();
        resultVO.setCode(ResultCodeEnums.OK.getCode());
        resultVO.setData(data);
        resultVO.setMsg(ResultCodeEnums.OK.getMsg());
        return resultVO;
    }


    /**
     * 是否成功
     * @param result
     * @param <T>
     * @return
     */
    public static <T> boolean isSuccess(ResultVo<T> result){
        if(result == null || result.getCode() == null){
            return false;
        }
        return ResultCodeEnums.OK.getCode().intValue() == result.getCode().intValue();
    }



    /**
     * 获取结果
     * @param result
     * @param <T>
     * @return
     */
    public static <T> T getData(ResultVo<T> result){
        if(isSuccess(result)){
            return result.getData();
        }
        log.error("返回结果数据异常:{}", Objects.isNull(result) ? "结果为空" : result.getMsg());
        return null;
    }

    public static ResultVo error(Integer code , String msg) {
        ResultVo resultVO = new ResultVo();
        resultVO.setMsg(msg);
        resultVO.setCode(code);
        return resultVO;
    }

    public static ResultVo error(Integer code , String msg,Object data) {
        ResultVo resultVO = new ResultVo();
        resultVO.setMsg(msg);
        resultVO.setCode(code);
        resultVO.setData(data);
        return resultVO;
    }


    public static <T> ResultVo<T> error( String msg) {
        ResultVo<T> resultVO = new ResultVo<>();
        resultVO.setMsg(msg);
        resultVO.setCode(ResultCodeEnums.ERROR.getCode());
        return resultVO;
    }


    public static ResultVo error(ResultCodeEnums resultCodeEnums) {
        ResultVo resultVO = new ResultVo();
        resultVO.setMsg(resultCodeEnums.getMsg());
        resultVO.setCode(resultCodeEnums.getCode());
        return resultVO;
    }
}
